package cn.ges.file;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author gespent@163.com
 * @date 2019/07/22 10:52
 */
public class FileUtil {

    public static String readFile(String filePath) throws IOException {

        try (FileReader fileReader = new FileReader(filePath)) {
            try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
                String line = bufferedReader.readLine();
                final StringBuilder stringBuilder = new StringBuilder();
                while (line != null) {
                    stringBuilder.append(line);
                    line = bufferedReader.readLine();
                }

                bufferedReader.close();
                fileReader.close();
                return stringBuilder.toString();
            }
        }
    }


    public static void creatFile(String filePath, String text) {
        File file = new File(filePath);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;

        try {
            if (!file.exists()) {
                boolean hasFile = file.createNewFile();
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }

            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            //写入内容
            osw.write(text);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
